package com.java2007.hotel.filter;

import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * @author Reckeys
 * @version V1.0
 * @date 2021/01/08
 **/

public class CodingFilter implements Filter {
    private String[] extNames;

    @Override
    public void init(FilterConfig filterConfig) throws ServletException {
        //获取初始化数据
        String names = filterConfig.getInitParameter("extName");
        //将字符串分隔成数组
        extNames = names.split(",");

    }

    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
        //强转
        HttpServletRequest request = (HttpServletRequest) servletRequest;
        HttpServletResponse response = (HttpServletResponse) servletResponse;

        //获取request请求的uri
        String uri = request.getRequestURI();

        boolean flag = false;

        //判断后缀
        for (String extName : extNames) {
            if (uri != null) {
                if (uri.endsWith(extName)) {
                    flag = true;
                    break;
                }
            }
        }
        if (!flag){
            request.setCharacterEncoding("UTF-8");
            response.setContentType("text/html;charset=UTF-8");
        }
        filterChain.doFilter(request, response);
    }

    @Override
    public void destroy() {

    }
}
